<template>
    <div class="">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-message"></i>&nbsp;新增商品</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div style="max-width:1000px;padding:10px 0 30px 0px">
                <el-alert
                    title="建议上传的图片压缩之后再上传，便于小程序请求图片资源加载速度快"
                    type="warning"
                    show-icon>
                </el-alert>
            </div>
            <el-form ref="form" label-width="160px">
                <el-form-item label="项目分类：">
                    <el-cascader
                        :options="options"
                        expand-trigger="hover"
                        v-model="selectedOptions"
                        @change="handleChange">
                    </el-cascader>
                </el-form-item>
                <el-form-item label="商品封面图：">
                    <div class="sola-upload clearfix">
                        <div class="sola-left clearfix" v-show="bannerPicture.length>0">
                            <div v-for="(item, index) in bannerPicture" class="sola-flex" :key="index">
                                <img  :src="item" />
                                <span class="delete" @click="delPicture(index,item,1)"><i class="el-alert__icon el-icon-error"></i></span>
                            </div>
                        </div>
                        <div class="sola-file-box">
                            <el-button type="primary" plain>上传图片<i class="el-icon-upload el-icon--right"></i></el-button>
                            <input class="btn-file" type="file" @change="uploadBanner"/>
                            <span style="color:red;padding-left:10px;">最多上传五张，(比例规范 宽大于750)建议上传的轮播图比例是1：1 示例750X750,每张图片控制在1MB以下 </span>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="商品标题：">
                    <el-input v-model="title" placeholder="请输入商品标题" style="width:600px"></el-input>
                </el-form-item>

                <el-form-item label="商品规格信息：">
                    <div class="clearfix">
                        <div v-for="(item,index) in skuProp" style="padding-bottom:10px;" :key="index">
                            <el-input v-model="item.spec"  placeholder="请输入规格名称" style="width:160px" clearable></el-input>
                            <el-input v-model="item.price" type="number" placeholder="请输入规格原价" style="width:160px"></el-input>
                            <el-input v-model="item.discount_price" type="number" placeholder="请输入规格优惠价" style="width:160px"></el-input>
                            <el-input v-model="item.stock" type="number" placeholder="请输入规格库存数" style="width:160px"></el-input>
                            <el-button type="danger" icon="el-icon-delete" @click="delGoodsSku(item,index)"></el-button>
                        </div>
                        <div style="padding-top:5px;">
                            <el-button type="primary" plain @click="addGoodsSku"><i class="el-icon-plus"></i>&nbsp;&nbsp;新增规格信息</el-button>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="商品详情图：">
                    <div class="sola-upload clearfix">
                        <div class="sola-left clearfix" v-show="detailPicture.length>0">
                            <div v-for="(item, index) in detailPicture" class="sola-flex" :key="index">
                                <img  :src="item" />
                                <span class="delete" @click="delPicture(index,item,2)"><i class="el-alert__icon el-icon-error"></i></span>
                            </div>
                            
                        </div>
                        <div class="sola-file-box">
                            <el-button type="primary" plain>上传图片<i class="el-icon-upload el-icon--right"></i></el-button>
                            <input class="btn-file" type="file" accept="image/*" @change="uploadDetail"/>
                            <span style="color:red;padding-left:10px;">项目说明、项目规则、拼团说明、拼团规则、商品详情图宽度750*自适应（高度不限制）,图片建议分割几张图片上传,每张图片控制在1MB以下</span>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="是否推荐商品：">
                    <el-radio v-model="is_recommend" label="0" border >否</el-radio>
                    <el-radio v-model="is_recommend" label="1" border>是</el-radio>
                    <span>(提示：推荐商品对应的数据，是商城的推荐商品)</span>
                </el-form-item>
                <el-form-item label="是否热销商品：">
                    <el-radio v-model="is_hot" label="0" border >否</el-radio>
                    <el-radio v-model="is_hot" label="1" border>是</el-radio>
                     <span>(提示：推荐商品对应的数据，是商城的热销商品；首页热销爆款更多列表)</span>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onAddGoods">确认发布</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
            <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">取 消</el-button>
                <el-button type="primary" @click="deleteRow">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    name:"goodsList",
    data() {
        return {
            idx:0,//当前记录的下标
            delVisible:false,
            selectedOptions:[],//选中的商品分类
            options:[],//分类数据
            accept: 'image/gif, image/jpeg, image/png, image/jpg', //图片上传类型
            typeId:'', //当前要删除图片的类型   1封面图 2详情图
            bannerPicture:[],//存放的商品轮播图
            detailPicture:[],//存放的商品详情图
            title:'',//商品标题
            skuProp:[{spec_id:0,spec:'',price:"",discount_price:"",stock:""}],//规格、价格、优惠价、sku
            is_recommend:'0',//是否推荐商品：0否，1是
            is_hot:'0' //是否热卖商品：0否，1是
        }
    },
    //实例创建
    created(){
        //获取商品的分类
        this.getGoodsClassify();
        //获取商品信息
        //console.log(this.$route.params.goodsId);
        if(this.$route.params.goodsId && this.$route.params.goodsId>0){
            this.getGoodsInfo();
        }else{
            //跳转商品信息
            console.log("获取是商品ID失败")
        }
        
    },
    //计算属性
    computed:{

    },
    //方法
    methods: {
        //获取商品信息
        getGoodsInfo(){
            var _this = this;
            //获取商品信息
            this.$axios.get('/manage/goods/detail', {
                params: {
                    goodsId:this.$route.params.goodsId,
                }
            })
            .then(function (response) {
                // console.log("获取商品信息成功");
                // console.log(response);
                if(response.data.code==200){
                    var data = response.data.data;
                    //获取项目的分类  然后默认选中
                    let category =[];
                    category.push(data.category_level1);
                    category.push(data.category_level2);
                    _this.selectedOptions = category;
                    //封面图 不用转换 JSON格式
                    if(typeof(data.banner_img)!="object"){
                        _this.bannerPicture = JSON.parse(data.banner_img);
                    }else{
                        _this.bannerPicture = data.banner_img;
                    }
                    //详情图 不用转换 JSON格式
                    if(typeof(data.detail)!="object"){
                        _this.detailPicture = JSON.parse(data.detail);
                    }else{
                        _this.detailPicture = data.detail;
                    }
                    //获取商品标题
                    _this.title = data.name;
                    //获取商品规格信息
                    if(data.specList.length>0){
                        //表示有商品规格信息
                        data.specList.forEach((item)=>{
                            item.spec_id = item.id;
                        });
                        _this.skuProp = data.specList;
                    }
                    //是否推荐
                    _this.is_recommend =""+data.is_recommend+"";
                    _this.is_hot = ""+data.is_hot+"";


                }else{
                    console.log("获取商品详情失败");
                }
            })
            .catch(function (error) {
                console.log(error);
            });
        },
        //获取商品的分类
        getGoodsClassify(){
            var _this = this;
            this.$axios.get('/manage/goods/categoryList', {
                params: {
                    pageIndex:1,
                    pageSize:999
                }
            })
            .then(function (response) {
                // console.log(response);
                if(response.data.code==200){
                    var data = response.data.data;
                    var array = [];
                    data.forEach(element => {
                        //console.log(element);
                        let obj ={};
                        obj.value = element.id;
                        obj.label = element.name;
                        var cities = [];
                        element.children.forEach(rows=>{
                            let subObj ={};
                            subObj.value = rows.id;
                            subObj.label = rows.name;
                            cities.push(subObj);
                        });
                        obj.children =cities;
                        array.push(obj);
                    });
                    //console.log(array);
                    _this.options = array;
                }else{

                    console.log("获取分类失败");
                }
            })
            .catch(function (error) {
                console.log(error);
            });
        },
        //确定删除图片
        deleteRow(){
            if(this.typeId==1){
                //封面图
                this.bannerPicture.splice(this.idx,1);
            }else if(this.typeId==2){
                //详情图
                this.detailPicture.splice(this.idx,1);
            }else if(this.typeId==3){
                //删除规格信息
                this.skuProp.splice(this.idx,1);
            }
            //console.log(this.bannerPicture)
            // this.tableData.splice(this.idx,1);
            this.$message.success('删除成功');
            this.delVisible = false;
        },
        //删除图片
        delPicture(index, row,typeId){
            //当前记录的下标
            this.idx = index;
            this.typeId = typeId;
            this.delVisible = true;
            
        },
        // file 文件源转换base64 并且按照最低像素压缩
        getBase64(file,callback){
            //图片文件转base64
            var maxWidth = 640;  
            if(file.files && file.files[0]){  
                var thisFile = file.files[0];  
                var reader = new FileReader();  
	            reader.readAsDataURL(file.files[0]);  
                reader.onload = function(event){  
                    var imgUrl = event.target.result;  
                    /*var img = new Image();  
                    img.onload = function(){  
                        var canvasId = 'canvasBase64Imgid',  
                        canvas = document.getElementById(canvasId);  
                        if(canvas!=null){document.body.removeChild(canvas);}  
                        var canvas = document.createElement("canvas");  
                        canvas.innerHTML = 'New Canvas';  
                        canvas.setAttribute("id", canvasId);  
                        canvas.style.display='none';  
                        document.body.appendChild(canvas);  
                        canvas.width = this.width;  
                        canvas.height = this.height;  
                        var imageWidth = this.width,   
                        imageHeight = this.height;  
                        if (this.width > maxWidth){  
                            imageWidth = maxWidth;  
                            imageHeight = this.height * maxWidth/this.width;  
                            canvas.width = imageWidth;  
                            canvas.height = imageHeight;  
                        }  
                        var context = canvas.getContext('2d');  
                        context.clearRect(0, 0, imageWidth, imageHeight);  
                        context.drawImage(this, 0, 0, imageWidth, imageHeight);  
                        var base64 = canvas.toDataURL('image/png',1);  
                        canvas.remove();
                        
                    }  
                    img.src = imgUrl; */ 
                    callback(imgUrl);
                }  
            }  
        },
        //触发项目封面图 file
        uploadBanner(event){
            var _event = event;
            var _this = this;
            let reader =new FileReader();  
            let img1=event.target.files[0];  
            let type=img1.type;//文件的类型，判断是否是图片  
            let size=img1.size;//文件的大小，判断图片的大小
            const files = event.target;  
            if(this.accept.indexOf(type) == -1){  
                this.$message({
                    message: '请选择gif,jpeg,png,jpg格式图片上传',
                    type: 'warning'
                });
                return false;  
            }  
            else if(size>1048576){  
                this.$message({
                    message: '请选择1M以内的图片上传',
                    type: 'warning'
                }); 
                return false;  
            }else if (typeof(FileReader) === 'undefined') {
                this.$notify.error({
                    title: '错误',
                    message: '抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！'
                });

            }else {
                //把图片转换成功base64
                _this.getBase64(files,(url)=>{
                    var base = url ;
                    const querystring = require('querystring');
                    const param ={
                        base64:base
                    }
                    this.$axios.post('/api/common/upload/base64',querystring.stringify(param)).then(response=>{
                        // console.log(response);
                        if(response.data.code==200){
                            this.$message({
                                message: '恭喜你，图片上传成功',
                                type: 'success'
                            });
                            this.bannerPicture.push(response.data.data);
                            
                        }else{
                            this.$notify.error({
                                title: '上传图片失败',
                                duration:2000,
                                message: '失败原因：'+response.data.msg
                            });
                        }

                    }).catch(error=>{
                        console.log(error);
                    });
                    
                });
                
            }
        },
        //触发项目详情图 file 
        uploadDetail(event){
            var _event = event;
            var _this = this;
            let reader =new FileReader();  
            let img1=event.target.files[0];  
            let type=img1.type;//文件的类型，判断是否是图片  
            let size=img1.size;//文件的大小，判断图片的大小
            const files = event.target;  
            if(this.accept.indexOf(type) == -1){  
                this.$message({
                    message: '请选择gif,jpeg,png,jpg格式图片上传',
                    type: 'warning'
                });
                return false;  
            }  
            else if(size>1048576){  
                this.$message({
                    message: '请选择3M以内的图片上传',
                    type: 'warning'
                }); 
                return false;  
            }else if (typeof(FileReader) === 'undefined') {
                this.$notify.error({
                    title: '错误',
                    message: '抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！'
                });

            }else {
                //把图片转换成功base64
                _this.getBase64(files,(url)=>{
                    var base = url ;
                    const querystring = require('querystring');
                    const param ={
                        base64:base
                    }
                    this.$axios.post('/api/common/upload/base64',querystring.stringify(param)).then(response=>{
                        // console.log(response);
                        if(response.data.code==200){
                            this.$message({
                                message: '恭喜你，图片上传成功',
                                type: 'success'
                            });
                            this.detailPicture.push(response.data.data);
                            
                        }else{
                            this.$notify.error({
                                title: '上传图片失败',
                                duration:2000,
                                message: '失败原因：'+response.data.msg
                            });
                        }

                    }).catch(error=>{
                        console.log(error);
                    });
                    
                });
            }
        },
        //获取项目的
        handleChange(){
        },
        //删除商品规格信息
        delGoodsSku(item,index){
            if(this.skuProp.length<=1){
                this.$notify({title: '警告',message: '规格信息至少要填一项',type: 'warning'});
            }else{
                this.idx = index;
                this.typeId = 3;
                this.delVisible = true;
            }
        },
        //新增商品规格信息
        addGoodsSku(){
            var object = {spec_id:0,spec:'',price:"",discount_price:"",stock:""};
            this.skuProp.push(object);
        },
        toptipSkuFlag(){
            var flag = false;
            var reg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
            var  stockReg= /^\+?[1-9][0-9]*$/;
            this.skuProp.every((item)=>{
                if(item.spec==""){
                    this.$notify.info({title: '提示',message: '请填写商品规格'});
                    flag = true;
                    return false;//跳出循环
                }else if(item.price==""){
                    this.$notify.info({title: '提示',message: '请填写商品规格原价'});
                    flag = true;
                    return false;//跳出循环
                }else if(!reg.test(item.price)){
                    this.$notify.info({title: '提示',message: '请填写正确的商品规格原价,且金额最多两位小数点'});
                    flag = true;
                    return false;//跳出循环
                    
                }else if(parseFloat(item.price)<0){
                    this.$notify.info({title: '提示',message: '商品规格原价至少要大于零'});
                    flag = true;
                    return false;//跳出循环
                }else if(item.discount_price==""){
                    flag = true;
                    this.$notify.info({title: '提示',message: '请填写商品规格优惠价'});
                    return false;//跳出循环
                }else if(!reg.test(item.discount_price)){
                    flag = true;
                    this.$notify.info({title: '提示',message: '请填写正确的商品规格优惠价,且金额最多两位小数点'});
                    return false;//跳出循环
                }else if(item.stock==""){
                    flag = true;
                    this.$notify.info({title: '提示',message: '请填写商品规格库存数'});
                    return false;//跳出循环
                }else if(parseInt(item.stock)=="NaN"){
                    flag = true;
                    this.$notify.info({title: '提示',message: '规格库存数只能是数字类型'});
                    return false;//跳出循环
                }else if(!stockReg.test(item.stock) && item.stock!="0"){
                    flag = true;
                    this.$notify.info({title: '提示',message: '规格库存数是正整数'});
                    return false;//跳出循环
                }
            });
            return flag;
        },
        //确认编辑商品
        onAddGoods(){
            if(this.selectedOptions.length<1){
                this.$notify.info({title: '提示',message: '请先选择商品分类'});
                return false;
            }
            else if(this.bannerPicture.length<1){
                this.$notify.info({title: '提示',message: '请先上传商品封面图'});
                return false;
            }else if(this.title==""){
                this.$notify.info({title: '提示',message: '请填写商品标题'});
                return false;
            }
            else if(this.toptipSkuFlag()){}
            else if(this.detailPicture.length<1){
                this.$notify.info({title: '提示',message: '请上传商品的详情图'});
                return false;
            }
            else{
                let param ={}
                param.id = this.$route.params.goodsId;
                param.categoryLevel1=this.selectedOptions[0],//一级分类ID
                param.categoryLevel2=this.selectedOptions[1],//二级分类ID
                param.name=this.title,//商品名
                param.imgList=JSON.stringify(this.bannerPicture), // 封面图  图片，数组JSON字符串
                param.detail=JSON.stringify(this.detailPicture),//详情，数组JSON字符串
                this.skuProp.forEach((value)=>{
                    // object = {spec:'',price:"",discount_price:"",stock:""};
                    value.price =parseFloat(value.price);
                    value.discount_price =parseFloat(value.discount_price); //dou
                    value.stock =parseInt(value.stock);  //修改类型  整数类型
                });
                param.specJson=JSON.stringify(this.skuProp)//商品规格列表，数组JSON字符串，格式：[{"spec": "100g", "price": 200, "discount_price": 180, "stock": 99}]
                param.is_recommend=this.is_recommend; //是否推荐商品：0否，1是
                param.is_hot=this.is_hot; //是否热卖商品：0否，1是
                // console.log(param)
                //调用提交方法
                this.saveGoods(param);
            }
        },
        //提交商品信息上传
        saveGoods(param){
            var _this =this;
            //  _this.$router.push('/projectAdd');
            const querystring = require('querystring');
            this.$axios.post('/manage/goods/update',querystring.stringify(param)).then(response=>{
                //console.log(response);
                if(response.data.code==200){
                    this.$message({
                        message: '恭喜你，编辑成功',
                        type: 'success'
                    });
                    setTimeout(function(){
                        _this.$router.push('/goods');
                        // this.$router.push({path:''})
                    },1500);
                    
                }else{
                    this.$notify.error({
                        title: '编辑失败',
                        duration:2000,
                        message: '失败原因：'+response.data.msg
                    });
                }
            }).catch(error=>{
                console.log(error);
            });
        }
    }
}
</script>
<style lang="stylus" scoped>
    .el-form-item .el-cascader{
        width :400px;
    }
    .el-cascader-menus .el-cascader-menu{
        width :240px
    }
    .sola-upload{
        .sola-left{
            width :100%;
            height :auto;
            .sola-flex{
                float:left
                width: 360px;
                height: 180px;
                margin-bottom 20px;
                margin-right:15px;
                position:relative;
                .delete{
                    position:absolute;
                    top:2px;
                    right:13px;
                    color: #f56c6c;
                    display:inline-block;
                    padding:5px 5px;
                    .el-alert__icon{font-size:28px;cursor:pointer}
                }
                img {
                    width:100%;
                    height:100%;
                }
            }
        }
        .sola-file-box{
            position:relative;
            .btn-file{
                position:absolute;
                top:0;
                left:0;
                z-index 1;
                opacity:0;
                width :120px;
                height :40px;
                outline: 0;
                background-color :none;
                cursor:pointer;
            }
        }

    }
</style>


